package com.hippy.erya.config.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 */
@Slf4j
public class CrossOriginFilter implements Filter {

    private static final String CONTENT_TYPE = "application/json";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        String terminalType=req.getHeader("terminalType");
        log.info("terminalType={}",terminalType);

        // 设置允许在请求头携带的参数
        res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,CF,USER,terminalType," +
                "timestamp,userId,version,sessionId");
        // 指定了当浏览器的credentials设置为true时是否允许浏览器读取response的内容，该值为true时，Access-Control-Allow-Origin的值不能为*号
        res.setHeader("Access-Control-Allow-Credentials", "true");
        String origin = Optional.ofNullable(req.getHeader("Origin")).orElse(req.getHeader("Referer"));
        // 判断一下来源，对正常访问进行来源判断
        if (!StringUtils.isEmpty(origin)) {
//                if (origin.indexOf("xx.xx.xx.xx:yyyy") > -1) {
            // 跨域
            res.setHeader("Access-Control-Allow-Origin", origin);
            // res.setHeader("Access-Control-Allow-Origin", "*");
//                }
        }
        // 让swagger和druid等通过
        else {
            res.setHeader("Access-Control-Allow-Origin", "*");
        }
        // 表示在3600秒内，不需要再发送OPTIONS预检验请求，可以在指定时间缓存该结果
        res.setHeader("Access-Control-Max-Age", "3600");
        // 跨域 Header
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        if (req != null && res != null && "H5".equals(terminalType)) {
            //
            res.setContentType(CONTENT_TYPE);

        }
        // 不对OPTIONS请求作处理
        if (null != servletRequest && null != servletResponse &&
                "OPTIONS".equals(((HttpServletRequest) servletRequest).getMethod())) {
            ((HttpServletResponse) servletResponse).setStatus(200);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }
}
